# -*- coding: utf-8 -*-
# 模板管理模块

import os
import shutil
import requests
import zipfile
import tempfile
import pandas as pd
import logging

# 默认模板URLs (可配置)
DEFAULT_TEMPLATES = {
    'mobaxterm': 'https://example.com/templates/mobaxterm.moba',
    'securecrt': 'https://example.com/templates/securecrt.ini',
    'xshell': 'https://example.com/templates/xshell.xsh'
}

def get_template_path(client_type, template_dir='templates'):
    """获取模板文件路径"""
    template_files = {
        'mobaxterm': 'mobaxterm.moba',
        'securecrt': 'securecrt.ini',
        'xshell': 'xshell.xsh'
    }
    
    if client_type not in template_files:
        return None
    
    template_path = os.path.join(template_dir, template_files[client_type])
    return template_path if os.path.exists(template_path) else None

def download_template(client_type, output_dir='templates', url=None):
    """下载模板文件"""
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    if url is None:
        if client_type not in DEFAULT_TEMPLATES:
            print(f"错误: 未知的客户端类型 {client_type}")
            return False
        url = DEFAULT_TEMPLATES[client_type]
    
    template_files = {
        'mobaxterm': 'mobaxterm.moba',
        'securecrt': 'securecrt.ini',
        'xshell': 'xshell.xsh'
    }
    
    if client_type not in template_files:
        print(f"错误: 未知的客户端类型 {client_type}")
        return False
    
    output_path = os.path.join(output_dir, template_files[client_type])
    
    try:
        response = requests.get(url, stream=True)
        if response.status_code == 200:
            with open(output_path, 'wb') as f:
                for chunk in response.iter_content(chunk_size=1024):
                    if chunk:
                        f.write(chunk)
            print(f"已下载模板: {output_path}")
            return True
        else:
            print(f"下载模板失败，状态码: {response.status_code}")
            return False
    except Exception as e:
        print(f"下载模板失败: {e}")
        return False

def create_default_template(client_type, output_dir='templates'):
    """创建默认模板文件"""
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    templates = {
        'mobaxterm': {
            'filename': 'mobaxterm.moba',
            'content': '[Bookmarks_Entry]\nSubRep=\nImgNum=41\nSsh=1\nHost=192.168.100.10\nPassword=\nUser=root\nName=hyperv-centos79\n',
            'encoding': 'utf-8'
        },
        'securecrt': {
            'filename': 'securecrt.ini',
            'content': '[SSH2]\nHost=192.168.100.10\nProtocol=SSH2\nPort=22\nUserName=root\nPassword=\nColor=1\nLogonTimeout=30\nClosedTimeout=30\n',
            'encoding': 'utf-8'
        },
        'xshell': {
            'filename': 'xshell.xsh',
            'content': '[CONNECTION]\nHost=192.168.100.10\nProtocol=SSH\nPort=22\nUserName=root\nPassword=\nAutoLogin=true\n',
            'encoding': 'utf-8'
        }
    }
    
    if client_type not in templates:
        print(f"错误: 未知的客户端类型 {client_type}")
        return False
    
    template_info = templates[client_type]
    output_path = os.path.join(output_dir, template_info['filename'])
    
    try:
        with open(output_path, 'w', encoding=template_info['encoding']) as f:
            f.write(template_info['content'])
        print(f"已创建模板: {output_path}")
        return True
    except Exception as e:
        print(f"创建模板失败: {e}")
        return False

def create_machine_list_template(output_path, format='xlsx'):
    """创建机器列表模板文件"""
    try:
        # 创建示例数据
        data = {
            'hostname': ['server-example-1', 'server-example-2'],
            'IP': ['192.168.1.101', '192.168.1.102'],
            'username': ['root', 'admin'],
            'password': ['password123', 'admin123'],
            'role': ['network', 'vm']
        }
        
        # 创建DataFrame
        df = pd.DataFrame(data)
        
        # 根据格式保存
        if format.lower() == 'csv':
            df.to_csv(output_path, index=False)
        else:  # 默认为Excel
            with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
                df.to_excel(writer, sheet_name='Sheet1', index=False)
                # 调整列宽
                worksheet = writer.sheets['Sheet1']
                for i, col in enumerate(df.columns):
                    # 设置列宽为字段名长度或内容长度的最大值再加10
                    max_length = max(df[col].astype(str).map(len).max(), len(col)) + 5
                    worksheet.column_dimensions[chr(65 + i)].width = max_length
        
        return True
    except Exception as e:
        logging.error(f"创建机器列表模板失败: {e}")
        return False 